var isGoing = false;
module.exports = {
  getPagesJson(attr = '') {
    let json = typeof PAGESJSON == 'object' ? PAGESJSON : {};
    if (attr) {
      const get = require('lodash/get');
      return get(json, attr);
    }
    return json;
  },
  getCurrentPage() {
    let pages = getCurrentPages();
    let page = pages[pages.length - 1];
    return page;
  },
  go(path, query = {}, success = undefined, fail = undefined) {
    if (!path || path == '#') {
      return false;
    }
    if (path.startsWith('mini://')) { //小程序跳转
      let [, appId, appPath] = path.match(/mini:\/\/(\w+)(.*)/) || [];
      uni.navigateToMiniProgram({
        appId: appId,
        path: appPath,
        success: (res) => {
          success?.call?.(res)
        },
        fail: (err) => {
          fail?.call?.(err);
        }
      });
      return true;
    } else if (path.startsWith('tel://')) { //播打电话
      let number = path.replace("tel://", "");
      uni.makePhoneCall({
        phoneNumber: number,
        success: (res) => {
          success?.call?.(res)
        },
        fail: (err) => {
          fail?.call?.(err);
        }
      })
      return true;
    } else if (path.startsWith('https://') || path.startsWith('http://')) { 
      
      if(window && window?.location){
        window.location.href = path;
      }else{
        //域名跳转，进入webview
        query.src = path;
        path = '/pages/webview/webview';
      }
    
    } else if (path.startsWith('map://')) {
      let [location, name, address] = path.match(/map:\/\/(.*)\|(.*)\|(.*)/) || ['0,0'];
      let [latitude, longitude] = location.split(',');
      uni.openLocation({
        latitude: latitude,
        longitude: longitude,
        name: name,
        address: address
      });
      return true;
    }
    const uri = this.buildUri(path, query);
    let pages = getCurrentPages();
    let page = pages[pages.length - 1];
    //同一个页面，重新刷新
    if ('/' + page.route == uri.path()) {
      return this.redirect(path, query, success, fail);
    }
    let router;
    let list = this.getPagesJson('tabBar.list');
    if (Array.isArray(list) && list.length > 0 && list.findIndex(item => '/' + item.pagePath == uri.path()) >= 0) {
      router = uni.switchTab;
    } else {
      router = uni.navigateTo;
    }
    isGoing = true;
    router({
      url: uri.toString(),
      success: success,
      fail: fail,
      complete: () => {
        isGoing = false;
      }
    });
    return true;
  },
  redirect(url, query = {}, success = undefined, fail = undefined) {
    const uri = this.buildUri(url, query);
    isGoing = true;
    uni.redirectTo({
      url: uri.toString(),
      success: success,
      fail: fail,
      complete: () => {
        isGoing = false;
      }
    });
    return true;
  },
  goBack(delta, success = null) {
    if (isGoing) {
      return false;
    }
    let pages = getCurrentPages();
    if (typeof delta == 'string') {
      isGoing = false;
      let index = pages.findIndex(page => {
        return page.$page.fullPath == delta
      });
      if (index < 0) {
        this.go(delta)
      } else {
        let back = pages.length - index - 1;
        uni.navigateBack({
          delta: back
        })
      }
      return true;
    } else {
      //if (typeof delta == 'object' || typeof delta == 'number') {
      isGoing = true;
      uni.navigateBack({
        delta: typeof delta == 'number' ? delta : 1,
        complete: () => {
          isGoing = false;
          if (success) {
            success.call(this);
          }
        }
      });
      return true;
    }
    isGoing = false;
    console.log('nowhere to go');
    return false;
  },
  goStart() {
    let pages = this.getPagesJson('pages');
    let path = '/' + (pages?. [0]?.path || 'pages/index/index');
    uni.reLaunch({
      url: path
    })
  },
  buildUri(path, query = {}) {
    const URI = require('urijs');
    let url = path;
    if (['string', 'object'].includes(typeof query)) {
      url = URI(url).addQuery(query || {});
    }
    if (URI(url).is('absolute')) {
      url = URI('/pages/webview/index').addQuery({
        url
      });
    }
    return url;
  },
}
